package com.holylin.learning.java.language.innerClass;

import java.util.HashMap;
import java.util.Map;

public abstract class ShapeFactory {
	protected abstract Shape create();

	private static Map<String, ShapeFactory> factories = new HashMap<String, ShapeFactory>();

	public static void addFactory(String id, ShapeFactory f) {
		factories.put(id, f);
	}

	public static final Shape createShape(String id) {
		if (!factories.containsKey(id)) {
			try {
				Class.forName("com.holylin.learning.java.language.innerClass."
						+ id);
			} catch (ClassNotFoundException e) {
				throw new RuntimeException("Bad shape creation : " + id);
			}
		}
		return ((ShapeFactory) factories.get(id)).create();
	}

	public static void main(String[] args) {
		String[] ids = new String[] { "Circle", "Square", "Square", "Circle" };
		for (int i = 0; i < ids.length; i++) {
			Shape shape = ShapeFactory.createShape(ids[i]);
			shape.draw();
			shape.erase();
		}
	}
}
